<template>
  <div class="login-container">
    <el-form :model="loginForm" :rules="fieldRules" ref="loginForm" label-position="left" label-width="0px"
             class="demo-ruleForm login-container-form">
    <span class="tool-bar">
      <!-- 主题切换 -->
      <theme-picker style="float:right;" class="theme-picker" :default="themeColor"
                    @onThemeChange="onThemeChange"></theme-picker>
      <!-- 语言切换 -->
      <!-- <lang-selector class="lang-selector"></lang-selector>    -->
    </span>
      <h2 class="title" style="padding-left:22px;">系统登录</h2>
      <el-form-item prop="account">
        <el-input type="text" v-model="loginForm.account" auto-complete="off" placeholder="账号" clearable>
          <i slot="prefix"
             class="el-input__icon el-icon-user">
          </i>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="loginForm.password" auto-complete="off" placeholder="密码" clearable>
          <i slot="prefix"
             class="el-input__icon el-icon-lock">
          </i>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-col :span="12">
          <el-form-item prop="captcha">
            <el-input type="test" v-model="loginForm.captcha" auto-complete="off" placeholder="验证码, 单击图片刷新"
                      style="width: 100%;">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="1">&nbsp;</el-col>
        <el-col :span="11">
          <el-form-item>
            <img style="width: 100%;" class="pointer" :src="loginForm.src" @click="refreshCaptcha">
          </el-form-item>
        </el-col>
      </el-form-item>
      <!--<el-checkbox v-model="checked" checked class="remember">记住密码</el-checkbox>-->
      <el-form-item style="width:100%;">
        <!--<el-button type="primary" style="width:48%;" @click.native.prevent="reset">重 置</el-button>-->
        <el-button type="primary" style="width:100%;" @click.native.prevent="login" :loading="loading">登 录</el-button>
      </el-form-item>
    </el-form>
  </div>

</template>

<script>
  import {mapState} from 'vuex'
  import Cookies from "js-cookie"
  import ThemePicker from "@/components/ThemePicker"
  import LangSelector from "@/components/LangSelector"

  export default {
    name: 'Login',
    components: {
      ThemePicker,
      LangSelector
    },
    data() {
      // 验证码的验证逻辑
      let validateCaptcha = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入验证码'));
        } else {
          if (value.length !== 5) {
            callback(new Error('请输入正确位数验证码'));
            return;
          }
          const reg = /^[0-9a-zA-Z]+$/;
          if (!reg.test(value)) {
            callback(new Error('验证码只能包含数字字母'));
            return;
          }
          callback();
        }
      };
      return {
        loading: false,
        loginForm: {
          account: '',
          password: '',
          captcha: '',
          src: ''
        },

        fieldRules: {
          account: [
            {required: true, message: '请输入账号', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'}
          ],
          captcha: [
            {validator: validateCaptcha, trigger: 'blur'}
          ]
        },
        checked: true
      }
    },
    methods: {
      login() {
        // 判断表单是否通过验证
        this.$refs.loginForm.validate((valid) => {
          // 通过验证
          if (valid) {
            this.loading = true;
            let userInfo = {
              account: this.loginForm.account,
              password: this.loginForm.password,
              captcha: this.loginForm.captcha
            };
            // 登录
            this.$api.login.login(userInfo).then((res) => {
              if (res.msg != null) {
                this.$message({
                  message: res.msg,
                  type: 'error'
                });
                this.loading = false;
              } else {
                // 保存用户到本地会话
                sessionStorage.setItem('user', userInfo.account);
                // 要求重新加载导航菜单
                this.$store.commit('menuRouteLoaded', false);
                this.$router.push('/')  // 登录成功，跳转到主页
              }
              this.loading = false
            }).catch((res) => {
              this.$message({
                message: res.message,
                type: 'error'
              });
              this.loading = false;
            });
            // 未通过验证
          } else {
            return false;
          }
        });
      },
      /**
       * 刷新验证码
       */
      refreshCaptcha: function () {
        this.loginForm.src = this.global.baseUrl + "/captcha.jpg?t=" + new Date().getTime();
      },
      reset() {
        this.$refs.loginForm.resetFields()
      },
      // 切换主题
      onThemeChange: function (themeColor) {
        this.$store.commit('setThemeColor', themeColor)
      },
      // 显示从其他页面退回到登录页的错误信息
      showErrorMessage() {
        if (this.$route.params.errorMessage) {
          this.$message({
            message: this.$route.params.errorMessage,
            type: 'error'
          })
        }
      }
    },
    mounted() {
      this.showErrorMessage();
      this.refreshCaptcha()
    },
    computed: {
      ...mapState({
        themeColor: state => state.app.themeColor
      })
    }
  }
</script>

<style lang="scss" scoped>
  .login-container-form {
    -webkit-border-radius: 5px;
    border-radius: 5px;
    -moz-border-radius: 5px;
    background-clip: padding-box;
    margin: 100px auto;
    width: 350px;
    padding: 35px 35px 15px 35px;
    background: #fff;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;

    .title {
      margin: 0 auto 30px auto;
      text-align: center;
      color: #505458;
    }

    .remember {
      margin: 0 0 35px 0;
    }
  }

  .login-container {
    min-height: 100%;
    width: 100%;
    background-image: url("../assets/login.png");
    overflow: hidden;
  }
</style>
